﻿using DTcms.Core.Common.Helper;
using DTcms.Core.Model.ViewModels;

namespace DTcms.Core.Web.Helpers
{
    /// <summary>
    /// HTTP请求帮助类
    /// </summary>
    public class HttpHelper
    {
        static IHttpContextAccessor? _httpContextAccessor { get; set; }
        /// <summary>
        /// 依赖注入
        /// </summary>
        public HttpHelper(IServiceCollection services)
        {
            _httpContextAccessor = services.BuildServiceProvider().GetService<IHttpContextAccessor>();
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="url">接口地址</param>
        /// <param name="isCache">是否缓存</param>
        /// <returns>T类型</returns>
        public static T? Get<T>(string url, bool isCache = true) where T : class
        {
            //读取缓存
            if (isCache)
            {
                var model = MemoryCacheHelper.Get<T>(url);
                if (model != null)
                {
                    return model;
                }
            }
            var baseApi = $"{_httpContextAccessor?.HttpContext?.Request.Scheme}://{_httpContextAccessor?.HttpContext?.Request.Host}/api"; //获取API地址
            var expired = int.Parse(Appsettings.GetValue(new string[] { "ApiConfig", "Expired" }));
            //获取Token
            var token = _httpContextAccessor?.HttpContext?.Request.Cookies["dt_client_access_token"];
            ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
            //如果有Token则传过去
            if (!string.IsNullOrEmpty(token))
            {
                headers.Add(new KeyValuePair<string, string>("Authorization", $"Bearer {token}"));
            }
            var jsonData = RequestHelper.GetAsync($"{baseApi}{url}", headers).Result;
            //如果请求有错则抛出异常
            if (jsonData.statusCode != 200 && jsonData.statusCode != 204 && jsonData.statusCode != 404)
            {
                throw new ApplicationException(jsonData.reBody);
            }
            var result = JsonHelper.ToJson<T>(jsonData.reBody);
            //存入缓存
            if (isCache && result != null)
            {
                MemoryCacheHelper.Set(url, result, new TimeSpan(0, 0, expired));
            }
            return result;
        }

        /// <summary>
        /// 获取当前匹配站点信息
        /// </summary>
        public static SitesDto? GetCurrSite(string domain)
        {
            var model = MemoryCacheHelper.Get<SitesDto>(domain);
            if (model != null)
            {
                return model;
            }
            var baseApi = $"{_httpContextAccessor?.HttpContext?.Request.Scheme}://{_httpContextAccessor?.HttpContext?.Request.Host}/api"; //获取API地址
            var expired = int.Parse(Appsettings.GetValue(new string[] { "ApiConfig", "Expired" }));
            var jsonData = RequestHelper.GetAsync($"{baseApi}/client/site/view/0").Result;
            var list = JsonHelper.ToJson<List<SitesDto>>(jsonData);
            //查找匹配域名
            if (list != null)
            {
                SitesDto? siteModel = list.FirstOrDefault(x => x.Domains != null && x.Domains.Any(x => x.Domain != null && x.Domain.ToLower().Equals(domain.ToLower())));
                if(siteModel == null)
                {
                    siteModel = list.FirstOrDefault(x => x.IsDefault == 1);
                }
                //存入缓存
                if (siteModel != null)
                {
                    MemoryCacheHelper.Set(domain, siteModel, new TimeSpan(0, 0, expired), true);
                }
                return siteModel;
                
            }
            return null;
        }
    }
}
